#include "tool/placearctool.h"
#include "item/circulararcitem.h"
#include "command/additemcommand.h"

#include <QAction>

namespace SymbolEditor
{

    PlaceArcTool::PlaceArcTool(QObject *parent):
        PlacementTool(parent)
    {
        QAction *action = new QAction(QIcon::fromTheme("draw-halfcircle3"),
                                      "<b>P</b>lace an <b>A</b>rc <i>p,a</i>", nullptr);
        action->setShortcut(QKeySequence("p,a"));
        setAction(action);
        setToolGroup("interactive-tools");
    }

    PlaceArcTool::~PlaceArcTool()
    {

    }

    GraphicsItem *PlaceArcTool::beginInsert(const QPointF &pos)
    {
        m_item = new GraphicsCircularArcItem();
        m_item->setPos(pos);
        return m_item;
    }

    void PlaceArcTool::addPoint(int idx, const QPointF &pos)
    {
        movePoint(idx, pos);
    }

    void PlaceArcTool::freezePoint(int idx, const QPointF &pos)
    {
        Q_UNUSED(pos);

        if (idx != 3)
        {
            return;
        }
        emit commandRequested(nullptr);

        delete m_item;
        m_item = nullptr;

        resetTool();
    }

    bool PlaceArcTool::removePoint(int idx, const QPointF &pos)
    {
        int handleId;
        switch (idx)
        {
            case 0:
            case 1:
                return false; // Remove and delete Arc
            case 2:
                handleId = GraphicsCircularArcItem::RadiusHandle;
                break;
            case 3:
                m_item->setSpanAngle(0);
                handleId = GraphicsCircularArcItem::StartAngleHandle;
                break;
            default:
                // Fail loudly
                Q_ASSERT(idx < 4);
                return false;
        }
        QPointF p = m_item->mapFromScene(pos);
        m_item->handleAt(handleId)->setPos(p);
        return true; // Keep going
    }

    void PlaceArcTool::movePoint(int idx, const QPointF &pos)
    {
        QPointF p = m_item->mapFromScene(pos);
        switch (idx)
        {
            case 0:
                return;
            case 1:
                m_item->setRadius(p.x());
                break;
            case 2:
                m_item->handleAt(GraphicsCircularArcItem::StartAngleHandle)->setPos(p);
                m_item->handleAt(GraphicsCircularArcItem::SpanAngleHandle)->setPos(p);
                break;
            case 3:
                m_item->handleAt(GraphicsCircularArcItem::SpanAngleHandle)->setPos(p);
                break;
            default:
                // Fail loudly
                Q_ASSERT(idx < 5);
                return;
        }
    }

    void PlaceArcTool::endInsert(const QPointF &pos)
    {
        Q_UNUSED(pos);
    }

    void PlaceArcTool::cancelInsert()
    {

    }

}
